<template>
  <div class="resource-list">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item prop="name" label="资源名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item prop="url" label="资源路径">
            <el-input v-model="form.url"></el-input>
          </el-form-item>
          <el-form-item prop="categoryId" label="资源分类">
            <el-select
              v-model="form.categoryId"
              placeholder="请选择资源分类"
              clearable
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="item in resourceCategories"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="width: 250px">
            <el-button
              @click="onReset"
              :disabled="isLoading"
            >重置</el-button>
            <el-button
              type="primary"
              @click="onSubmit"
              :disabled="isLoading"
            >搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card class="box-card add-categray" :body-style="{ padding: '0' }">
        <el-button size="mini" @click="openAddResource">添加</el-button>
        <el-button size="mini" @click="$router.push({ path: '/resourceCategory' })">资源分类</el-button>
      </el-card>

      <el-table
        :data="resources"
        style="width: 100%; margin-bottom: 20px"
        v-loading="isLoading"
      >
        <el-table-column type="index" label="编号" width="100"></el-table-column>
        <el-table-column prop="name" label="资源名称" width="240"></el-table-column>
        <el-table-column prop="url" width="240" label="资源路径"></el-table-column>
        <el-table-column prop="description" width="240" label="描述"></el-table-column>
        <el-table-column prop="createdTime" label="添加时间"></el-table-column>
        <el-table-column width="180" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--
        total 总记录数
        page-size 每页大小
        分页组件会自动根据 total 和 page-size 计算出一共分多少页
       -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :disabled="isLoading"
        :current-page.sync="form.current"
        :page-sizes="[5, 10, 20]"
        :page-size="form.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
      </el-pagination>
    </el-card>

    <el-dialog title="添加资源" :visible.sync="dialogVisible" width="600px">
      <el-form :model="resourceForm">
        <el-form-item label="资源名称" :label-width="formLabelWidth">
        <el-input v-model="resourceForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="资源路径" :label-width="formLabelWidth">
        <el-input v-model="resourceForm.url" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="资源路径" :label-width="formLabelWidth">
        <el-select v-model="resourceForm.categoryId" placeholder="请选择活动区域">
            <el-option :label="cate.name" :value="cate.id" :key="cate.id" v-for="cate in resourceCategories"></el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
        <el-input v-model="resourceForm.description" type="textarea" :rows="6" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSaveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { setTime } from '@/utils/timer'
import { getResourcePages, saveOrUpdateResources, deleteResource } from '@/services/resource'
import { getResourceCategories } from '@/services/resource-category'
import { Form } from 'element-ui'

export default Vue.extend({
  name: 'ResourceList',
  data () {
    return {
      resources: [], // 资源列表
      form: {
        name: '',
        url: '',
        current: 1, // 默认查询第1页数据
        size: 5, // 每页大小
        categoryId: null // 资源分类
      },
      totalCount: 0,
      resourceCategories: [], // 资源分类列表
      isLoading: true, // 加载状态
      dialogVisible: false,
      isSavingOrUpdate: false,
      formLabelWidth: '100px',
      resourceForm: {
        id: '',
        name: '',
        categoryId: -1,
        url: '',
        description: ''
      }
    }
  },

  created () {
    this.loadResources()
    this.loadResourceCategories()
  },

  methods: {
    async loadResourceCategories () {
      const { data } = await getResourceCategories()
      this.resourceCategories = data.data
      this.resourceForm.categoryId = data.data[0].id
    },

    async loadResources () {
      this.isLoading = true // 展示加载中状态
      const { data } = await getResourcePages(this.form)
      this.resources = data.data.records.map((item: any) => {
        item.createdTime = setTime(item.createdTime)
        return item
      })
      this.totalCount = data.data.total
      this.isLoading = false // 关闭加载中状态
    },

    onSubmit () {
      this.form.current = 1 // 筛选查询从第 1 页开始
      this.loadResources()
    },

    openAddResource () {
      const item: any = this.resourceCategories[0]
      this.resourceForm = {
        id: '',
        name: '',
        categoryId: item.id,
        url: '',
        description: ''
      }
      this.dialogVisible = true
    },

    async handleEdit (item: any) {
      this.resourceForm = {
        id: item.id,
        name: item.name,
        categoryId: item.categoryId,
        url: item.url,
        description: item.description
      }
      this.dialogVisible = true
    },

    async onSaveOrUpdate () {
      if (!this.isSavingOrUpdate) {
        this.isSavingOrUpdate = true
        const { data } = await saveOrUpdateResources(this.resourceForm)
        if (data.code === '000000') {
          this.dialogVisible = false
          this.$message.success('添加成功')
          this.loadResources() // 更新数据列表
        } else {
          this.$message.info('添加失败，请重新添加！')
        }
        this.isSavingOrUpdate = false
      }
    },

    async handleDelete (item: any) {
      this.$confirm('确认删除吗？', '删除提示', {})
        .then(async () => { // 确认执行这里
          // 请求删除操作
          const { data } = await deleteResource(item.id)
          if (data.code === '000000') {
            this.$message.success('删除成功')
            this.loadResources() // 更新数据列表
          }
        })
        .catch(err => { // 取消执行这里
          console.log(err)
          this.$message.info('已取消删除')
        })
    },

    handleSizeChange (val: number) {
      this.form.size = val
      this.form.current = 1 // 每页大小改变重新查询第1页数据
      this.loadResources()
    },

    handleCurrentChange (val: number) {
      // 请求获取对应页码的数据
      this.form.current = val // 修改要查询的页码
      this.loadResources()
    },

    onReset () {
      (this.$refs.form as Form).resetFields()
      this.form.current = 1 // 重置回到第1页
      this.loadResources()
    }
  }
})
</script>

<style lang="scss">
.resource{
  .el-card{
    .el-card__header{
      .el-form{
        display: flex;
        justify-content: space-between;
        .el-form-item{
          margin-bottom: 0;
        }
      }

      .el-table{
        td{
          text-align: center;
        }
      }
    }
  }

  .el-card.add-categray{
    box-shadow: none;
    border: none;
    border-bottom: 1px solid #EBEEF5;
    border-radius: 0;
    padding-bottom: 20px;
  }

  .el-table{
    th,td{
      text-align: center;
    }
  }
}
</style>
